package com.like.banzipao.server.util.roomstate.playroomstate

import com.like.banzipao.server.model.Player
import com.like.banzipao.server.model.PlayerState
import com.like.banzipao.server.model.Poker
import com.like.banzipao.server.model.PokerState
import com.like.banzipao.server.model.Room
import com.like.banzipao.server.model.User
import com.like.banzipao.server.util.PlayRuleUtils
import com.like.banzipao.server.util.roomstate.BaseRoomState

/**
 * 玩牌阶段的一些方法实现
 */
abstract class PlayRoomState(room: Room) : BaseRoomState(room) {
    // 前一家出的牌，用于出牌时判断出牌规则
    protected val prePlayedPokers = mutableListOf<Poker>()

    final override fun playPlayed(user: User, ids: List<Int>): Boolean {
        val player = getPlayer(user) ?: return false
        val nextPlayer = player.nextPlayer() ?: return false
        val curPlayedPokers = player.getPokers(ids)
        if (curPlayedPokers.isEmpty()) {
            return false
        }
        val isValid = try {
            PlayRuleUtils.isValid(prePlayedPokers, curPlayedPokers)
        } catch (e: Exception) {
            false
        }
        if (!isValid) {
            return false
        }
        return onPlayPlayed(player, nextPlayer, curPlayedPokers)
    }

    final override fun playPass(user: User) {
        val player = getPlayer(user) ?: return
        val nextPlayer = player.nextPlayer() ?: return
        onPlayPass(player, nextPlayer)
    }

    abstract fun onPlayPlayed(player: Player, nextPlayer: Player, curPlayedPokers: List<Poker>): Boolean

    abstract fun onPlayPass(player: Player, nextPlayer: Player)

    protected fun Player.nextValidPlayerTurn(state: PlayerState) {
        nextValidPlayer()?.apply {
            this.state = state
            this.getPokers().forEach {
                if (it.state == PokerState.PLAY_PLAYED) {
                    it.state = PokerState.PLAY_DECKS
                }
            }
        }
    }
}